package com.shaiMiMi;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

import android.os.Handler;
import android.os.Message;

public class ZTcpSocketThread extends Thread implements Serializable{
	private InetSocketAddress		mInetSocketAddress;
	private	int						mConnectOutTime = 5000;
	private Vector<ZPackage>		mVecPackages = new Vector<ZPackage>();
	private TcpReadHelper			mTcpReadHelper;
	private Handler					mHandler = null;
	private int 					mThreadId = -1;
	private Socket 					mSocket = null;

	public ZTcpSocketThread(String host, int port, Handler handler, int iThreadId) {
		mInetSocketAddress = new InetSocketAddress(host, port);
		mHandler = handler;
		mThreadId = iThreadId;
	}

	public ZTcpSocketThread(ZTcpSocketThread srcSocket) {
		mInetSocketAddress = new InetSocketAddress(srcSocket.mInetSocketAddress.getHostName(),
				srcSocket.mInetSocketAddress.getPort());
		mHandler = srcSocket.mHandler;
		mThreadId = srcSocket.mThreadId;
	}

	public void SetConnectOutTime(int iConnectOutTime) {
		mConnectOutTime = iConnectOutTime;
	}

	public void AppendPack(ZPackage pack) {
		mVecPackages.add(pack);
	}

	public Socket GetSocket() {
		return mSocket;
	}

	private void ConnectServer(){
		try {
			mSocket.connect(mInetSocketAddress, mConnectOutTime);
			ConnectInfo.GetInstance().SetConnected(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run(){
		mSocket = new Socket();
		ConnectServer();
		mTcpReadHelper = new TcpReadHelper(mSocket);
		while(true)
		{
			if (mSocket.isClosed()) {
				ConnectServer();
			}

			if (!mSocket.isConnected()) {
				ConnectServer();
			}
			try {

				if (!mVecPackages.isEmpty()) {
					ZPackage pack = mVecPackages.firstElement();
					OutputStream outputStream = mSocket.getOutputStream();
					outputStream.write(pack.GetAllSendByte());
					if (!ConnectInfo.GetInstance().IsTestMode()) { //测试压力模式不进行删除
						mVecPackages.remove(pack);
					}
				}

				if (mTcpReadHelper.Read()) {
					byte[] packData = mTcpReadHelper.GetPackDataArray();
					ZPackage newPackage = ZPackageFactory.CreatePackage(packData);
					mTcpReadHelper.Reset();

					Message msg = new Message();
					msg.what = mThreadId;
					msg.obj = newPackage;
					mHandler.sendMessage(msg);
				}
			} catch (UnknownHostException e) {
				ConnectInfo.GetInstance().SetConnected(false);
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    }
}
